package com.one.blocks.rbac.security;

import com.one.blocks.mvc.util.ScopeWebRequestHelper;
import com.one.blocks.rbac.domain.SysRole;
import com.one.blocks.rbac.enums.RoleTypeEnum;
import com.one.blocks.rbac.manager.SysMenuManager;
import com.one.blocks.rbac.manager.SysRoleManager;
import com.one.blocks.rbac.util.SubjectHelper;
import com.one.blocks.security.authz.AuthorizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

import static com.one.blocks.rbac.constant.RbacConstant.ScopeRequest.ROLES_OF_USER_ID;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-08-12 10:19:09
 */
@Component
public class RbacPermissionService implements AuthorizeService {

    @Autowired
    private SysMenuManager sysMenuManager;

    @Autowired
    private SysRoleManager sysRoleManager;

    @Override
    public boolean hasPermission(String permission) {
        // 查询用户对应角色
        final Integer userId = SubjectHelper.getSubjectId();
        List<SysRole> sysRoleList = ScopeWebRequestHelper.get(ROLES_OF_USER_ID + userId,
                () -> sysRoleManager.findByUserId(userId));
        if (CollectionUtils.isEmpty(sysRoleList)) {
            return false;
        }

        // 超级管理员直接通过
        if (sysRoleList.stream().anyMatch(i -> RoleTypeEnum.ADMIN.match(i.getType()))) {
            return true;
        }

        // 根据角色查询是否有权限
        for (SysRole sysRole : sysRoleList) {
            if (sysMenuManager.findPermissionByRole(sysRole.getId()).contains(permission)) {
                return true;
            }
        }
        return false;
    }
}
